// Copyright (c) 2019 Presto Labs Pte. Ltd.
// Author: jaewon

#include "coin1/fastfeed/view/base.h"

#include <cmath>

#include <glog/logging.h>

#include "coin1/fastfeed/view/view_collection.h"

namespace fastfeed {
namespace view {

void ViewBase::SetViewKey(const ViewKey& view_key) { view_key_ = view_key; }

void ViewBase::Subscribe(std::function<void(const ViewBase*)> callback) {
  callbacks_.push_back(callback);
}

void ViewBase::InvokeCallbacks() {
  for (const auto& callback : callbacks_) {
    callback(this);
  }
}

void BuilderBase::Init(ViewCollection* view_collection) {
  if (feed_type() != proto::FEED_TYPE_CUSTOM) {
    view_collection->SubscribeFeed(
        feed_type(),
        symbol(),
        std::bind(&BuilderBase::OnFeed, this, std::placeholders::_1));
  } else {
    view_collection->SubscribeCustomFeed(
        custom_feed_type(),
        symbol(),
        std::bind(&BuilderBase::OnFeed, this, std::placeholders::_1));
  }
  InitBuilder();
}

void BuilderBase::OnFeed(const proto::Feed& feed) {
  bool res = UpdateByProto(feed);
  if (res) {
    InvokeCallbacks();
  }
}

}  // namespace view
}  // namespace fastfeed
